package com.winit.dataInit;

import com.winit.Application;
import com.winit.feature.model.Feature;
import com.winit.feature.repository.FeatureRepository;
import com.winit.page.model.Page;
import com.winit.page.repository.PageRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.StringUtils;

import java.util.Iterator;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class FeaturePathProcessor {

    private static Logger logger = LoggerFactory.getLogger(FeaturePathProcessor.class);

    private static final boolean FORCE_UPDATE = false;

    @Autowired
    private FeatureRepository featureRepository;

    @Autowired
    private PageRepository pageRepository;

    @Test
    public void updateFeaturePath(){
        Iterator<Feature> features = featureRepository.findAll().iterator();
        while (features.hasNext()){
            Feature feature = features.next();
            if (StringUtils.isEmpty(feature.getPath()) || FORCE_UPDATE){
                String pageId = feature.getOriginalPageId();
                if (StringUtils.isEmpty(pageId)){
                    logger.info("no page id found for feature, id:" + feature.getId());
                    continue;
                }
                Page page = this.pageRepository.findOne(pageId);
                if (null == page){
                    logger.info("no page found for feature, feature_id:" + feature.getId() + ", page_id:" + pageId);
                    continue;
                }

                String title = page.getTitle();
                String menuPath = page.getMenuPath();
                if (menuPath.endsWith("/")){
                    menuPath = menuPath + title;
                }else {
                    menuPath = menuPath + "/" + title;
                }
                feature.setPath(menuPath);
                this.featureRepository.save(feature);
            }
        }
    }

}
